# coding:utf-8
import random
import time

from django.http import request

import models

# def js2PhpTime(jsdate):
#     jsdate=str(jsdate)
#     a=jsdate.split("/")
#     ret="0-0-0"+a[1]+"-"+a[2]+"-"+a[3]
#   # if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)@', $jsdate, $matches)==1){
#   #   $ret = mktime(matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
#   #   # //echo $matches[4] ."-". $matches[5] ."-". 0  ."-". $matches[1] ."-". $matches[2] ."-". $matches[3];
#   # }
#   # else if(preg_match('@(\d+)/(\d+)/(\d+)@', $jsdate, $matches)==1){
#   #   $ret = mktime(0, 0, 0, $matches[1], $matches[2], $matches[3]);
#   #
#   #   # //echo 0 ."-". 0 ."-". 0 ."-". $matches[1] ."-". $matches[2] ."-". $matches[3];
#   # }
#     return ret


def php2JsTime(Date):
    timeArray = time.gmtime(Date)
    otherStyleTime = time.strftime("%m/%d/%Y %H:%M", timeArray)
    return otherStyleTime


def php2MySqlTime(Date):
    timeArray = time.gmtime(Date)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M",timeArray)
    return otherStyleTime


def addCalendar(st, et, sub, ade):
  ret = {}
  ret['IsSuccess'] = True
  ret['Msg'] = 'add success'
  ret['Data'] =random.randint(1,32767)
  return ret



def addDetailedCalendar(st, et, sub, ade, dscr, loc, color, tz):
  ret = {}
  ret['IsSuccess'] = True
  ret['Msg'] = 'add success'
  ret['Data'] = random.randint(1,32767)
  return ret


def listCalendarByRange(sd, ed, cnt):
  ret = {}
  ret['events'] = []
  ret["issort"] =True
  ret["start"] = time.strftime("%m/%d/%Y %H:%M", time.gmtime(sd))
  ret["end"] = time.strftime("%m/%d/%Y %H:%M",time.gmtime(ed))
  ret['error'] = None
  ret['id'] = None
  title = ['班会', '单元测试', '期中考试', '期末考试', '小测验','放假']
  location = ['Lodan', 'Newswer', 'Belion', 'Moore', 'Bytelin']
  i=0
  while(i<cnt):
      rsd = random.randint(sd,ed)
      red=random.randint(3600,10800)
      if random.randint(0,10)>8:
          alld=1
      else:
          alld=0

      ret['events'].append([
        random.randint(10000, 99999),
        title[random.randint(0,4)],
        php2JsTime(rsd),
        php2JsTime(red),
        random.randint(0,1),
        alld,
        0,
        random.randint(-1,13),
        1,
        location[random.randint(0,4)],
          ''
        ])
      i+=1


  return ret


def listCalendar(day, type):
    day=day[0:10]
    day=int(day)
    st=0
    et=0
    cnt=0
    if type==u'month':
        st=get_month_begin(day)
        et=get_month_begin(day,1)
        cnt=50
    elif type==u'week':
        st=get_week_begin(day)
        et=get_week_begin(day,1)
        cnt = 20
    elif type==u'day':
        st=get_day_begin(day)
        et=get_day_begin(day,1)
        cnt=5
    return listCalendarByRange(st, et, cnt)
# phpTime = js2PhpTime(day);
#
# if type=="month":
#   switch(type){
#     case "month":
#       st = mktime(0, 0, 0, date("m", phpTime), 1, date("Y", phpTime));
#       et = mktime(0, 0, -1, date("m", phpTime)+1, 1, date("Y", phpTime));
#       cnt = 50;
#       break;
#     case "week":
#       //suppose first day of a week is monday
#     monday =1
# #     monday  =  date("d", phpTime) - date('N', phpTime) + 1;
# #       //echo date('N', $phpTime);
#     st = mktime(0,0,0,date("m", phpTime), monday, date("Y", phpTime));
#     et = mktime(0,0,-1,date("m", phpTime), monday+7, date("Y", phpTime));
#       $cnt = 20;
#       break;
#     case "day":
#       $st = mktime(0, 0, 0, date("m", $phpTime), date("d", $phpTime), date("Y", $phpTime));
#       $et = mktime(0, 0, -1, date("m", $phpTime), date("d", $phpTime)+1, date("Y", $phpTime));
#       $cnt = 5;
#       break;
#   }
#   //echo $st . "--" . $et;
#   return listCalendarByRange(st, et, cnt);
# }

def updateCalendar(id, st, et):
  ret = []
  ret['IsSuccess'] = True
  ret['Msg'] = 'Succefully'
  return ret


def updateDetailedCalendar(id, st, et, sub, ade, dscr, loc, color, tz):
  ret = []
  ret['IsSuccess'] = True
  ret['Msg'] = 'Succefully'
  return ret


def removeCalendar(id):
  ret = []
  ret['IsSuccess'] = True
  ret['Msg'] = 'Succefully'
  return ret


# header('Content-type:text/javascript;charset=UTF-8')
# method=request.GET.get('method')
# if method=="add":
#     ret=addCalendar(request.POST.get("CalendarStartTime"),request.POST.get("CalendarEndTime"),request.POST.get("CalendarTitle"),request.POST.get("IsAllDayEvent"))
# elif method=="list":
#     ret=listCalendar(request.POST.get("showdate"),request.POST.get("showdate"))
# elif method=="update":
#     ret=listCalendar(request.POST.get("calendarId"),request.POST.get("CalendarStartTime"),request.POST.get("CalendarEndTime"))
# elif method=="remove":
#     ret=removeCalendar(request.POST.get("calendarId"))
# elif method=="adddetails":
#     id = request.GET.get("id")
#     st = request.POST.get("stpartdate") + " " +request.POST.get("stparttime")
#     et =request.POST.get("etpartdate") +" " +request.POST.get("etparttime")
#     if(id):
#         ret = updateDetailedCalendar(id, st, et,
#             request.POST.get("Subject"), IsAllDayEvent(),
#             request.POST.get("Description"),
#             request.POST.get("Location"), request.POST.get("colorvalue"), request.POST.get("timezone"))
#
#     else:
#         ret = addDetailedCalendar(st, et,
#             request.POST.get("Subject"), IsAllDayEvent(), request.POST.get("Description"),
#             request.POST.get("Location"), request.POST.get("colorvalue"), request.POST.get("timezone"))

def IsAllDayEvent( request):
    if request.POST.get("IsAllDayEvent"):
        return 1
    else:
        return 0


# echo json_encode(ret)



def get_day_begin(ts = time.time(),N = 0):
    """
    N为0时获取时间戳ts当天的起始时间戳，N为负数时前数N天，N为正数是后数N天
    """
    return int(time.mktime(time.strptime(time.strftime('%Y-%m-%d',time.localtime(ts)),'%Y-%m-%d'))) + 86400*N

def get_week_begin(ts = time.time(),N = 0):
    """
    N为0时获取时间戳ts当周的开始时间戳，N为负数时前数N周，N为整数是后数N周，此函数将周一作为周的第一天
    """
    w = int(time.strftime('%w',time.localtime(ts)))
    return get_day_begin(int(ts - (w-1)*86400)) + N*604800

def get_month_begin(ts = time.time(),N = 0):
    """
    N为0时获取时间戳ts当月的开始时间戳，N为负数前数N月，N为正数后数N月
    """
    month_day = {1:31,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
    cur_y,cur_m,cur_d = [int(x) for x in time.strftime('%Y-%m-%d',time.localtime(ts)).split('-')]
    if (cur_y%4 == 0 and cur_y%100 != 0) or cur_y%400 == 0:
        month_day[2] = 29
    else:
        month_day[2] = 28
    t = get_day_begin(ts) - (cur_d-1)*86400
    real_month = N + cur_m
    if real_month == cur_m:
        return t
    if N > 0:
        if real_month <= 12:
            for x in xrange(cur_m,real_month):
                t += month_day[x]*86400
        if real_month > 12:
            for x in xrange(cur_m,13):
                t += month_day[x]*86400
            t = get_month_begin(t,real_month - 13)
    if N < 0:
        if real_month >= 1:
            for x in xrange(real_month,cur_m):
                t -= month_day[x]*86400
        if real_month < 1:
            for x in xrange(1,cur_m):
                t -= month_day[x]*86400
            t -= month_day[12]*86400
            t = get_month_begin(t,real_month)
    return t